package com.roger.cphelper;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.CalendarContract;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class MainActivity extends AppCompatActivity {
    private static String TAG = "Debug" + MainActivity.class.getSimpleName();
    private String defaultPkg,pkg;
    Button btn,btn2,btn3,btn4;
    public static receiveHandler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermission(this);
        handler = new receiveHandler();

        final EditText text = findViewById(R.id.text);
        btn =findViewById(R.id.button);
        btn2 =findViewById(R.id.button2);
        btn3 =findViewById(R.id.button3);
        btn4 =findViewById(R.id.button4);

        defaultPkg = Telephony.Sms.getDefaultSmsPackage(this);
        pkg = this.getPackageName();

        if(defaultPkg!=null){
            if(!defaultPkg.equals(pkg)){
                Intent intent=new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
                intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, pkg);
                startActivity(intent);
            }
        }

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = new Message();
                        msg.arg1=0;
                        handler.sendMessage(msg);
                        final int count =Integer.parseInt(text.getText().toString());
                        for(int i=0;i<count;i++) {
                            addContact(name(i), phone(), "test" + i + "@lenovo.com", "上海浦东新区" + i + "号");
                        }
                        Message msg1 = new Message();
                        msg1.arg1=1;
                        handler.sendMessage(msg1);
                        //Toast.makeText(MainActivity.this, "add contact success.", Toast.LENGTH_LONG).show();
                    }
                }).start();

            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(defaultPkg!=null){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.arg1=2;
                            handler.sendMessage(msg);
                            final int count =Integer.parseInt(text.getText().toString());
                            for(int i=0;i<count;i++) {
                                addCallLog(phone());
                            }
                            Message msg1 = new Message();
                            msg1.arg1=3;
                            handler.sendMessage(msg1);
                        }
                    }).start();
                }else{
                    btn2.setClickable(false);
                    btn2.setText("该设备不支持添加通话记录！");
                }
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(defaultPkg!=null){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.arg1=4;
                            handler.sendMessage(msg);
                            String nowPkg = Telephony.Sms.getDefaultSmsPackage(MainActivity.this);
                            if(!nowPkg.equals(pkg)){
                                Message msg0 = new Message();
                                msg0.arg1=100;
                                handler.sendMessage(msg0);
                            }else{
                                final int count =Integer.parseInt(text.getText().toString());
                                if(count==95599){
                                    SimpleDateFormat dateFormat = new SimpleDateFormat("MM月dd日HH时mm分", Locale.CHINA);
                                    addSms(String.valueOf(95599),"【中国农业银行】您尾号1888的农行账户于"+dateFormat.format(new Date()) +
                                            "完成一笔消费交易，金额为-16999.00，余额为389080031.82。");
                                }else{
                                    for(int i=0;i<count;i++) {
                                        addSms(phone(),"Test"+i);
                                    }
                                }
                                Message msg1 = new Message();
                                msg1.arg1=5;
                                handler.sendMessage(msg1);
                            }
                        }
                    }).start();
                }else{
                    btn3.setClickable(false);
                    btn3.setText("该设备不支持添加短信！");
                }
            }
        });

        btn4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = new Message();
                        msg.arg1=6;
                        handler.sendMessage(msg);
                        final int count =Integer.parseInt(text.getText().toString());
                        long  time = System.currentTimeMillis();
                        for(int i=0;i<count;i++) {
                            time -= 86400000L;
                            addCalendar("Test"+i,time);
                        }
                        Message msg1 = new Message();
                        msg1.arg1=7;
                        handler.sendMessage(msg1);
                    }
                }).start();
            }
        });
    }

    private void addContact(String name, String phoneNum,String email,String address){
        ContentResolver cr = getContentResolver();
        ContentValues cv = new ContentValues();
        //首先向RawContacts.CONTENT_URI执行一个空值插入，目的是获取系统返回的rawContactId
        Uri uri = cr.insert(ContactsContract.RawContacts.CONTENT_URI, cv);
        long rawContactId = ContentUris.parseId(uri);

        uri = Data.CONTENT_URI;
        String raw_contact_id =Data.RAW_CONTACT_ID;

        cv.put(raw_contact_id, rawContactId);
        cv.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
        cv.put(StructuredName.GIVEN_NAME, name);
        cr.insert(uri,cv);
        cv.clear();

        cv.put(raw_contact_id, rawContactId);
        cv.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
        cv.put(Phone.NUMBER, phoneNum);
        cv.put(Phone.TYPE, Phone.TYPE_MOBILE);
        cr.insert(uri, cv);
        cv.clear();

        cv.put(raw_contact_id, rawContactId);
        cv.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
        cv.put(Email.DATA, email);
        cv.put(Email.TYPE, Email.TYPE_WORK);
        cr.insert(uri, cv);
        cv.clear();

        cv.put(raw_contact_id, rawContactId);
        cv.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);
        cv.put(StructuredPostal.DATA, address);
        cv.put(StructuredPostal.TYPE, StructuredPostal.TYPE_HOME);
        cr.insert(uri, cv);
        cv.clear();
    }

    private void addCallLog(String phoneNum){
        ContentResolver cr = getContentResolver();
        ContentValues cv = new ContentValues();
        cv.clear();
        cv.put(CallLog.Calls.CACHED_NAME, "");
        cv.put(CallLog.Calls.NUMBER, phoneNum);
        cv.put(CallLog.Calls.TYPE, "");
        cv.put(CallLog.Calls.DATE,System.currentTimeMillis());
        cv.put(CallLog.Calls.DURATION, "");
        cv.put(CallLog.Calls.NEW, "0");
        cr.insert(CallLog.Calls.CONTENT_URI, cv);
    }

    private void addSms(String phoneNum,String body){
        ContentResolver cr=getContentResolver();
        ContentValues cv=new ContentValues();
        cv.put(Telephony.Sms.ADDRESS,phoneNum);
        cv.put(Telephony.Sms.DATE, System.currentTimeMillis());
        long dateSent=System.currentTimeMillis()-5000L;
        cv.put(Telephony.Sms.DATE_SENT,dateSent);
        cv.put(Telephony.Sms.READ,false);
        cv.put(Telephony.Sms.STATUS, Telephony.Sms.STATUS_COMPLETE);
        cv.put(Telephony.Sms.BODY, body);
        cv.put(Telephony.Sms.TYPE, Telephony.Sms.MESSAGE_TYPE_INBOX);
        cr.insert(Telephony.Sms.CONTENT_URI,cv);
    }

    private void addCalendar(String title,long date){
        ContentResolver cr=getContentResolver();
        ContentValues values = new ContentValues();
        values.clear();
        values.put(CalendarContract.Events.TITLE, title);
        values.put(CalendarContract.Events.DTSTART, date);
        values.put(CalendarContract.Events.DTEND,date);
        values.put(CalendarContract.Events.CALENDAR_ID, 1);
        values.put(CalendarContract.Events.ALL_DAY, 1);
        values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
        cr.insert(CalendarContract.Events.CONTENT_URI, values);

    }

    String []  first_name = {"赵","钱","孙","李","周","吴","郑","王","冯","程","楚","卫","蒋","沈","韩","杨"};
    String []  second_name = {"天","下","一","通","封","向","宁","应","的","命","斯","刚","俄","微","过","好"};
    String []  third_name = {"和","名","时","建","浩","工","前","萍","岳","山","水","充","侵","操","三","开"};


    private String name(){
        int a = new Random().nextInt(2);
        if(a==0) return first_name[new Random().nextInt(16)] + second_name[new Random().nextInt(16)];
        else return first_name[new Random().nextInt(16)] + second_name[new Random().nextInt(16)] + third_name[new Random().nextInt(16)];
    }

    private String name(int i){
        return "Test" + i;
    }

    private String phone(){
        StringBuilder num = new StringBuilder("13");
        for(int j=0;j<9;j++){
            num.append(new Random().nextInt(10));
        }
        return num.toString();
    }

    private void recoverDefaultPkg(){
        Intent intent=new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
        intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME,defaultPkg);
        startActivity(intent);
        Log.d(TAG,"Recover default SMS App");
    }

    @SuppressLint("HandlerLeak")
    public class receiveHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
           if(msg.arg1==0){
               btn.setText("联系人添加中,请稍后...");
               btn.setClickable(false);
           }else if (msg.arg1==1){
               btn.setText("联系人添加完成！");
           }else if (msg.arg1==2){
               btn2.setText("通话记录添加中,请稍后...");
               btn2.setClickable(false);
           }else if (msg.arg1==3){
               btn2.setText("通话记录添加完成！");
           }else if (msg.arg1==4){
               btn3.setText("短信添加中,请稍后...");
               btn3.setClickable(false);
           }else if (msg.arg1==5){
               recoverDefaultPkg();
               btn3.setText("短信添加完成！");
           }else if (msg.arg1==6){
               btn4.setText("日程活动添加中,请稍后...");
               btn4.setClickable(false);
           }else if (msg.arg1==7){
               btn4.setText("日程活动添加完成！");
           }else if (msg.arg1==100){
               btn3.setText("该程序不是短信默认应用，无法添加短信！请重新启动app，选择设置默认应用");
           }

        }
    }

    @SuppressLint({"MissingPermission", "HardwareIds"})
    public boolean isLTE(){
        TelephonyManager telManager = (TelephonyManager) MainActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (null == telManager.getImei()) return false;
            return !"".equals(telManager.getImei());
        } else {
            if (null == telManager.getDeviceId()) return false;
            return !"".equals(telManager.getDeviceId());
        }
    }

    @TargetApi(23)
    public static void checkPermission(AppCompatActivity activity) {
        boolean isGranted = true;
        if (Build.VERSION.SDK_INT >= 23) {
            if (activity.checkSelfPermission(Manifest.permission.WRITE_CONTACTS) != PERMISSION_GRANTED ||
                    activity.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PERMISSION_GRANTED ||
                    activity.checkSelfPermission(Manifest.permission.READ_CALL_LOG) != PERMISSION_GRANTED ||
                    activity.checkSelfPermission(Manifest.permission.WRITE_CALL_LOG) != PERMISSION_GRANTED ||
                    activity.checkSelfPermission(Manifest.permission.READ_CALENDAR) != PERMISSION_GRANTED ||
                    activity.checkSelfPermission(Manifest.permission.WRITE_CALENDAR) != PERMISSION_GRANTED ||
                    activity.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PERMISSION_GRANTED ) {
                isGranted = false;
            }
            if (!isGranted) {
                activity.requestPermissions(
                        new String[]{
                                Manifest.permission.WRITE_CONTACTS,
                                Manifest.permission.READ_CONTACTS,
                                Manifest.permission.READ_CALL_LOG,
                                Manifest.permission.WRITE_CALL_LOG,
                                Manifest.permission.READ_CALENDAR,
                                Manifest.permission.WRITE_CALENDAR,
                                Manifest.permission.READ_PHONE_STATE
                        },
                        102);
            }
        }
    }

}
